package com.jimmy.medical.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import com.jimmy.medical.service.IFileService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements IFileService {
    @Value("${file.serverPath}")
    private String serverPath;

    @Value("${file.downloadUrl}")
    private String downloadUrl;

    private SimpleDateFormat dateFormat;

    public FileServiceImpl() {
        dateFormat = new SimpleDateFormat("yyyyMMdd");
    }

    public String save(MultipartFile file) throws IOException {
        String filename = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
        String dirname = FilenameUtils.concat(serverPath, dateFormat.format(new Date()));
        String savedFilename = FilenameUtils.concat(dirname, filename);

        File dir = new File(dirname);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        File saveFile = new File(savedFilename);
        if (!saveFile.exists()) {
            saveFile.createNewFile();
        }

        file.transferTo(saveFile);
        return filename;
    }

    @Override
    public void delete(String path) throws IOException {
        String filename = FilenameUtils.concat(serverPath, path);
        File file = new File(filename);
        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public String getDownloadUrl() {
        return downloadUrl;
    }

    public String getServerPath() {
        return serverPath;
    }
}
